/*
 * Copyright (c) 2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "dyn_services_binding_key.h"

#include <stddef.h>

#include <tee_hw_ext_api.h>

#include "logger.h"

#define INIT_KEY_SIZE 48
#define INIT_KEY_VERSION 0x30

#define BINDING_KEY_SIZE 48
#define BINDING_KEY_VERSION 0x31

ResultCode GetServiceBindingKey(uint8_t *key, uint32_t *keyLength, uint32_t *kvn)
{
    if (key == NULL || keyLength == NULL || kvn == NULL) {
        return INVALID_PARA_NULL_PTR;
    }

    static const uint8_t salt[] = "se_base_service_binding_key";

    if (*keyLength < BINDING_KEY_SIZE) {
        LOG_ERROR("input size is not enough = %u", *keyLength);
        return INVALID_PARA_ERR_SIZE;
    }

    if (TEE_EXT_DeriveTARootKey(salt, sizeof(salt), key, BINDING_KEY_SIZE) != TEE_SUCCESS) {
        LOG_ERROR("deriva dek key error");
        return MEM_READ_ERR;
    }

    *keyLength = BINDING_KEY_SIZE;
    *kvn = BINDING_KEY_VERSION;
    return SUCCESS;
}